package com.todofun.common.app;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.BeanUtils;

import com.todofun.common.db.DBUtil;

public class BaseService {
	protected List queryByHQL(String hql) {
		Session session = DBUtil.getSession();
		List rs = session.createQuery(hql).list();
		DBUtil.closeSession();
		return rs;
	}
	
	protected List queryByHQL(String hql, Object... args) {
		Session session = DBUtil.getSession();
		Query query = session.createQuery(hql);
		for(int pIndex = 0;pIndex < args.length;pIndex++){
			query.setParameter(pIndex, args[pIndex]);
		}
		List rs = query.list();
		DBUtil.closeSession();
		return rs;
	}
	
	protected Object getVoByID(Class clazz,Long id) {
		Session session = DBUtil.getSession();
		Object rs = session.get(clazz, id);
		DBUtil.closeSession();
		return rs;
	}
	
	protected void saveVo(Object vo) {
		DBUtil.getSession().save(vo);
		DBUtil.closeSession();
	}
	
	protected void updateVo(Object vo) {
		DBUtil.getSession().update(vo);
		DBUtil.closeSession();
	}
	
	protected void delVoByID(Class clazz,Long id) {
		Session session = DBUtil.getSession();
		session.delete(session.load(clazz,id));
		DBUtil.closeSession();
	}
	
	protected void delVo(Object vo) {
		Session session = DBUtil.getSession();
		session.delete(vo);
		DBUtil.closeSession();
	}

	public void updateVo(BaseVo vo, String[] editignor) {
		Session session = DBUtil.getSession();
		Long id = vo.getId();
		Class clazz = vo.getClass();
		Object voInDB = session.load(clazz, id);
		BeanUtils.copyProperties(vo,voInDB,editignor);//vo -> voInDB copy property
		session.update(voInDB);
		DBUtil.closeSession();
	}
	
}
